//
//  UserInfoVC.m
//  BrushFace
//
//  Created by timer_q on 15/12/14.
//  Copyright © 2015年 Zzz. All rights reserved.
//
#import "MeRequest.h"
#import "UserInfoVC.h"
#import "UserDefaultCell.h"
#import "UserIconCell.h"
#import "NavHelper.h"
#import "CustomPickerView.h"
#import "CityController.h"
#import "EducationVC.h"
#import "NickVC.h"
#import "MySceneModel.h"
#import "AlreadyVerfifyVC.h"
@interface UserInfoVC ()<UITableViewDataSource,UITableViewDelegate>
{
    __weak IBOutlet UITableView *_tableView;
    NSArray *_dataArray;
    NSDictionary *_currentDict;
    NSMutableArray *_detailArray;
    
}
@property (nonatomic,strong)MySceneModel *reqmodel;
@property (nonatomic,strong)CustomPickerView *myPicker;
@end

@implementation UserInfoVC

#pragma mark - lifeCercle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self UIConfig];
    [self dataInit];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [_reqmodel fetchMyUserInfoAndCB:^(id output) {
        _currentDict = output;
        [_detailArray removeAllObjects];
        [self judgeIsNotEmptyWithStr:@"nickname"];
        [self judgeIsNotEmptyWithStr:@"sex"];
        [self judgeIsNotEmptyWithStr:@"age"];
        [self judgeIsNotEmptyWithStr:@"mobile"];
        if ([[NSString stringWithFormat:@"%@",_currentDict[@"fullnamed"]] integerValue]==1) {
            [_detailArray addObject:@"已认证"];
        }else
        {
            [_detailArray addObject:@"未认证"];
        }
        
            [self judgeIsNotEmptyWithKeyStr:@"education"];
       
        
            [self judgeIsNotEmptyWithKeyStr:@"livecity"];
       
        
            [self judgeIsNotEmptyWithKeyStr:@"homecity"];
        
       
            [self judgeIsNotEmptyWithKeyStr:@"industry"];
        
       
            [self judgeIsNotEmptyWithKeyStr:@"profession"];
       
        [_tableView reloadData];
    }];
}
#pragma mark - DataInit
- (void)UIConfig{
    [self.navBar setTitle:@"个人信息"];
    [self.navBar setLeftBtn:NAV_BAR_LEFT_BTN_TYPE_BLUE];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];

}
- (void)dataInit{
    NSArray *firstSectionArray = @[@"头像",@"昵称",@"性别",@"年龄",@"手机"];
    NSArray *secondSectionArray = @[@"实名认证"];
    NSArray *thirdSectionArray = @[@"学历学籍"];
    NSArray *fourthSectionArray = @[@"现居住地",@"家乡"];
    NSArray *fifthSectionArray = @[@"行业",@"公司-职业"];
    _dataArray = @[firstSectionArray,secondSectionArray,thirdSectionArray,fourthSectionArray,fifthSectionArray];
    [_tableView reloadData];
    _detailArray = [[NSMutableArray alloc]init];
    _reqmodel = [MySceneModel SceneModel];
}


- (void)judgeIsNotEmptyWithKeyStr:(NSString *)str
{
    if ([_currentDict[str] isNotEmpty])
    {
        if ([str isEqualToString:@"education"])
        {
            NSString *education = [NSString stringWithFormat:@"%@",_currentDict[str]];
            switch ([education intValue])
            {
                case 1:
                    education = @"高中以下";
                    break;
                case 2:
                    education = @"专科";
                    break;
                case 3:
                    education = @"本科";
                    break;
                case 4:
                    education = @"硕士";
                    break;
                case 5:
                    education = @"博士及以上";
                    break;
                case 6:
                    education = @"其他";
                    break;
                default:
                    break;
            }
        NSString *schoolname = [NSString stringWithFormat:@"%@",_currentDict[@"schoolname"]];
            
        schoolname = [self getSchoolNameOrAddressNameWithStr:schoolname andType:0];
            NSString *xueji = [NSString stringWithFormat:@"%@+%@",education,schoolname];
            [_detailArray addObject:xueji];
        }
        if ([str isEqualToString:@"livecity"])
        {
             NSString *livecity = [NSString stringWithFormat:@"%@",_currentDict[@"livecity"]];
            livecity = [self getSchoolNameOrAddressNameWithStr:livecity andType:1];
            [_detailArray addObject:livecity];
        }
        if ([str isEqualToString:@"homecity"])
        {
            NSString *homecity = [NSString stringWithFormat:@"%@",_currentDict[@"homecity"]];
            homecity = [self getSchoolNameOrAddressNameWithStr:homecity andType:1];
            [_detailArray addObject:homecity];
        }
        if ([str isEqualToString:@"industry"])
        {
             NSString *industry = [NSString stringWithFormat:@"%@",_currentDict[@"industry"]];
            NSString *path = [[NSBundle mainBundle]pathForResource:@"calling" ofType:@"plist"];
            NSArray *array = [[NSArray alloc]initWithContentsOfFile:path];
            industry = [array objectAtIndex:[industry intValue]-1];
            [_detailArray addObject:industry];
        }
        if ([str isEqualToString:@"profession"])
        {
            NSString *profession = [NSString stringWithFormat:@"%@",_currentDict[@"profession"]];
            [_detailArray addObject:profession];
        }

    }
    else
    {
        [_detailArray addObject:@""];
    }
    
}

- (NSString *)getSchoolNameOrAddressNameWithStr:(NSString *)str andType:(int)type
{
    NSString *resultStr = nil;
    NSString *proname = nil;
    NSData *data = nil;
    if (type == 0)
    {
        NSString * path = [[NSBundle mainBundle]pathForResource:@"college" ofType:@"json"];
        data = [[NSData alloc]initWithContentsOfFile:path];
    }
    else
    {
       NSString * path = [[NSBundle mainBundle]pathForResource:@"address" ofType:@"json"];
        data = [[NSData alloc]initWithContentsOfFile:path];
    }
    
    id jsondata = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
    NSArray *array = (NSArray *)jsondata;
    NSArray *keyArray = [str componentsSeparatedByString:@"-"];
    NSString *keyStr =keyArray[0];
    
    for (NSDictionary *dic in array)
    {
        if ([dic[@"value"] isEqualToString:keyStr])
        {
           
            proname = dic[@"name"];
            NSArray *subArray = dic[@"items"];
            for (NSDictionary *subDic in subArray) {
                if ([subDic[@"value"] isEqualToString:str])
                {
                    resultStr = subDic[@"name"];
                }
            }
        }
    }

    if (type == 0)
    {
        return resultStr;
    }
    else
    {
        NSString *str = [NSString stringWithFormat:@"%@-%@",proname,resultStr];
        return str;
    }
}

- (void)judgeIsNotEmptyWithStr:(NSString *)key{
    
    if ([_currentDict[key] isNotEmpty]) {
        
        if ([key isEqualToString:@"nickname"])
        {
            
            [_detailArray addObject:[self replayBaseStr:[NSString stringWithFormat:@"%@",_currentDict[@"nickname"]]]];
        }
        else
        {
            if ([key isEqualToString:@"sex"])
            {
                NSString *sexStr = nil;
                if ([_currentDict[key]isEqualToString:@"1"]) {
                    sexStr = @"男";
                }
                else if ([_currentDict[key]isEqualToString:@"2"])
                {
                    sexStr = @"女";
                }else
                {
                    sexStr = @"其他";
                }
                [_detailArray addObject:[NSString stringWithFormat:@"%@",sexStr]];
            }
            else
            {
                [_detailArray addObject:[NSString stringWithFormat:@"%@",_currentDict[key]]];
                
            }
        }
    }
    else
    {
        [_detailArray addObject:@""];
    }
}
- (NSString *)replayBaseStr:(NSString *)nickName{
    NSMutableString *nickN = [[NSMutableString alloc]initWithString:nickName];
    NSMutableString *retStr = [[NSMutableString alloc] init];
    for (int i=0; i<nickN.length; i+=4) {
        NSString *subStr = [NSString stringWithFormat:@"\\u%@",[nickN substringWithRange:NSMakeRange(i, 4)]];
        [retStr appendString:[self replaceUnicode:subStr]];
    }
    return retStr;
}

- (NSString *)replaceUnicode:(NSString *)unicodeStr {
    NSString *tempStr1 = [unicodeStr stringByReplacingOccurrencesOfString:@"\\u" withString:@"\\U"];
    NSString *tempStr2 = [tempStr1 stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];
    NSString *tempStr3 = [[@"\"" stringByAppendingString:tempStr2] stringByAppendingString:@"\""];
    NSData *tempData = [tempStr3 dataUsingEncoding:NSUTF8StringEncoding];
    NSString* returnStr = [NSPropertyListSerialization propertyListFromData:tempData
                                                           mutabilityOption:NSPropertyListImmutable
                                                                     format:NULL
                                                           errorDescription:NULL];
    
    return [returnStr stringByReplacingOccurrencesOfString:@"\\r\\n" withString:@"\n"];
}

#pragma mark - tableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [[_dataArray objectAtIndex:section] count];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return _dataArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *iconCellID = @"UserIconCell";
    static NSString *cellID = @"UserDefaultCell";
    if (indexPath.section==0&&indexPath.row==0) {
        UserIconCell *cell = [tableView dequeueReusableCellWithIdentifier:iconCellID];
        if (cell == nil) {
            cell = [UserIconCell loadBundleNib];
        }
        [cell.userIcon sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",HEADERIMAGE_FETCH,_currentDict[@"userid"]]]];
        return cell;
    }
    UserDefaultCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (cell == nil) {
        cell = [UserDefaultCell loadBundleNib];
    }
    NSString *text = [[_dataArray objectAtIndex:indexPath.section] objectAtIndex:indexPath.row];
    cell.userCellTitle.text = text;
    cell.userCellDefault.text = @"";
    if (_detailArray.count>0) {
        if (indexPath.section == 0) {
            cell.userCellDefault.text = [_detailArray objectAtIndex:indexPath.row-1];
            if (indexPath.row == 3) {
                NSString *str = cell.userCellDefault.text;
                if ([str isEqualToString:@"0"]) {
                    str = @"00";
                }
                cell.userCellDefault.text = [NSString stringWithFormat:@"%@后",str];
            }
        }
        if (indexPath.section == 1) {
            NSString *str = _detailArray[4];
            if ([str isEqualToString:@"未认证"]) {
                cell.userCellDefault.textColor = UIColorFromRGB(0xfe6b6b);
            }else{
                cell.userCellDefault.textColor = UIColorFromRGB(0x66d2ff);
            }
            cell.userCellDefault.text = _detailArray[4];
        }
        if (indexPath.section == 2) {
            cell.userCellDefault.text = _detailArray[5];
        }
        if (indexPath.section == 3)
        {
            if (indexPath.row == 0)
            {
                cell.userCellDefault.text = _detailArray[6];

            }
            else
            {
                cell.userCellDefault.text = _detailArray[7];
                

            }
        }
        if (indexPath.section == 4)
        {
            if (indexPath.row == 0)
            {
                cell.userCellDefault.text = _detailArray[8];
                
            }
            else
            {
                cell.userCellDefault.text = _detailArray[9];
                
                
            }
        }
    }
    
    if (indexPath.section == 0 && indexPath.row == 4) {
        cell.nextArrowImage.hidden = YES;
    }else{
        cell.nextArrowImage.hidden = NO;
    }
    
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0&&indexPath.row == 0) {
        return 70;
    }
    return 50;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section==0) {
        return 1;
    }
    return 10;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 10)];
    view.backgroundColor = UIColorFromRGB(ColorValueForBackView_Gray);
    return view;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section == 0)
    {
        switch (indexPath.row) {
            case 0:
            {
            
            }
                break;
            case 1:
            {
                //昵称
                NickVC *nickVC = [[NickVC alloc]init];
                nickVC.VCType = nick;
                nickVC.result = ^(NSString *resultStr)
                {
                    UserDefaultCell *cell = [tableView cellForRowAtIndexPath:indexPath];
                    cell.userCellDefault.text = resultStr;
                
                };
                [self.navigationController pushViewController:nickVC animated:YES];
            }
                break;

            case 2:
            {
                if (!_myPicker || _myPicker.pickerStyle == Age)
                {
                    if (_myPicker)
                    {
                        [_myPicker removeFromSuperview];
                    }
                    [self creatPickWithSty:Sexy andindexPath:indexPath];
                }
                
                
            }
                break;

            case 3:
            {
                if (!_myPicker || _myPicker.pickerStyle == Sexy)
                {
                    if (_myPicker)
                    {
                        [_myPicker removeFromSuperview];
                    }
                    [self creatPickWithSty:Age andindexPath:indexPath];
                }

 
            }
                break;

            case 4:
            {
                
            }
                break;

            default:
                break;
        }
    }
    
    else if (indexPath.section == 1)
    {
        UserDefaultCell *cell = [tableView cellForRowAtIndexPath:indexPath];
        if ([cell.userCellDefault.text isEqualToString:@"已认证"]) {
            AlreadyVerfifyVC * _vc = [[AlreadyVerfifyVC alloc]init];
            [_vc setHidesBottomBarWhenPushed:YES];
            [self.navigationController pushViewController:_vc animated:YES];
        }else{
            [NavHelper gotoRealNameVCWithType:2];
        }
    }
    else if (indexPath.section == 2)
    {
        EducationVC *eduVC = [[EducationVC alloc]init];
        [eduVC setHidesBottomBarWhenPushed:YES];
        eduVC.result = ^(NSString *str)
        {
            UserDefaultCell *cell = [tableView cellForRowAtIndexPath:indexPath];
            cell.userCellDefault.text = str;
        };
        [self.navigationController pushViewController:eduVC animated:YES];
    }
    else if (indexPath.section == 3)
    {
        CityController *cityVC = [[CityController alloc]init];
        if (indexPath.row == 0)
        {
            cityVC.VCType = cityLive;
        }
        else if (indexPath.row == 1)
        {
         cityVC.VCType = cityHome;
        }
       
        [self.navigationController pushViewController:cityVC animated:YES];
    
    }
    else if (indexPath.section == 4)
    {
        switch (indexPath.row) {
            case 0:
            {
                CityController *cityVC = [[CityController alloc]init];
                cityVC.VCType = calling;
                cityVC.calling = ^(NSString *callingStr)
                {
                    UserDefaultCell *cell = [tableView cellForRowAtIndexPath:indexPath];
                    cell.userCellDefault.text = callingStr;
                };
                [self.navigationController pushViewController:cityVC animated:YES];
            }
                break;
            case 1:
            {
                //行业职业
                NickVC *nickVC = [[NickVC alloc]init];
                nickVC.VCType = hangYe;
                nickVC.result = ^(NSString *resultStr)
                {
                    UserDefaultCell *cell = [tableView cellForRowAtIndexPath:indexPath];
                    cell.userCellDefault.text = resultStr;
                    
                };
                [self.navigationController pushViewController:nickVC animated:YES];

            }
            default:
                break;
        }
       
    }
}
-(void)creatPickWithSty:(pickerType)style andindexPath:(NSIndexPath *)indexPath
{
    CustomPickerView *pickView = [[[NSBundle mainBundle]loadNibNamed:@"CustomPickerView" owner:self options:nil]lastObject];
    pickView.pickerStyle = style;
    
    [pickView getResult:^(NSString *resultStr)
    {
        _myPicker = nil;
        switch (pickView.pickerStyle)
        {
            case Sexy:
            {
               [self sendSexyInfoWithDataStr:resultStr Index:indexPath];
            }
                break;
            case Age:
            {
               
                [self sendAgeInfoWithDataStr:resultStr Index:indexPath];
            }
                break;
            default:
                break;
        }
        
    }];
    pickView.cancelResult = ^(){
        _myPicker = nil;
    };
    
    [self.view addSubview:pickView];
    self.myPicker = pickView;
    pickView.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, 216);
    [UIView animateWithDuration:1 animations:^{
    pickView.frame = CGRectMake(0, SCREEN_HEIGHT-216, SCREEN_WIDTH, 216);
        }];

}

#pragma mark--上传性别
-(void)sendSexyInfoWithDataStr:(NSString *)dataStr Index:(NSIndexPath *)indexPath
{
    
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    if ([dataStr isEqualToString:@"男"])
    {
        [params setObject:@(1) forKey:@"sex"];
    }
    else if ([dataStr isEqualToString:@"女"])
    {
        [params setObject:@(2) forKey:@"sex"];
        
    }
    else if ([dataStr isEqualToString:@"其他"])
    {
        [params setObject:@(3) forKey:@"sex"];

    }
    
    [MeRequest sendUserDataWithType:sexy AndUserData:params success:^(NSDictionary *dic)
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            NSString *string = [NSString stringWithFormat:@"%@",dic[@"result"]];
            if ([string intValue]==1)
            {
                UserDefaultCell *cell = [_tableView cellForRowAtIndexPath:indexPath];
                cell.userCellDefault.text = dataStr;
            }

        });
            } error:^(NSError *error)
    {
        
    }];
}
#pragma mark--上传年龄
-(void)sendAgeInfoWithDataStr:(NSString *)dataStr Index:(NSIndexPath *)indexPath
{
    
        NSMutableDictionary *params = [NSMutableDictionary dictionary];
        [params setObject:dataStr forKey:@"age"];
        [MeRequest sendUserDataWithType:age AndUserData:params success:^(NSDictionary *dic)
         {
             dispatch_async(dispatch_get_main_queue(), ^{

             NSString *string = [NSString stringWithFormat:@"%@",dic[@"result"]];
             if ([string intValue]==1)
             {
                 UserDefaultCell *cell = [_tableView cellForRowAtIndexPath:indexPath];
                 NSString *newStr = dataStr;
                 if ([dataStr isEqualToString:@"0"]||[dataStr isEqualToString:@"00"]) {
                     newStr = @"00";
                 }
                 cell.userCellDefault.text = [NSString stringWithFormat:@"%@后",newStr];
             }
             });
         } error:^(NSError *error)
         {
             
         }];
    
}

-(void)setLiveCity:(NSString *)liveCity
{
    _liveCity = liveCity;
    NSIndexPath *index = [NSIndexPath indexPathForRow:0 inSection:3];
    UserDefaultCell *cell = [_tableView cellForRowAtIndexPath:index];
    cell.userCellDefault.text = _liveCity;
}
-(void)setHomeTown:(NSString *)homeTown
{
    _homeTown = homeTown;
    
    NSIndexPath *index = [NSIndexPath indexPathForRow:1 inSection:3];
    UserDefaultCell *cell = [_tableView cellForRowAtIndexPath:index];
    cell.userCellDefault.text = _homeTown;
}
@end
